package com.ims.task;

import com.ims.common.core.redis.RedisCache;
import com.ims.common.utils.DateUtils;
import com.ims.core.doc.service.ITSalOrderService;
import com.ims.core.doc.service.ITScSettlebillService;
import com.ims.core.erp.ErpApiUtil;
import com.ims.core.inconfig.service.ITSrmSupplierService;
import com.ims.core.saleconfig.service.ITSalBuyerService;
import com.ims.core.saleconfig.service.ITSalMaterialService;
import com.ims.system.service.ISysDictDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * ERP数据同步 task任务
 */
@Component("ErpDataTask")
public class ErpDataTask {
    //日志
    private static final Logger logger = LoggerFactory.getLogger(ErpDataTask.class);

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private ITSalBuyerService tSalBuyerService;

    @Autowired
    private ITSalMaterialService tSalMaterialService;

    @Autowired
    private ITSrmSupplierService tSrmSupplierService;

    @Autowired
    private ITSalOrderService tSalOrderService;

    @Autowired
    private ITScSettlebillService tScSettlebillService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 600s 锁竞争时间
     */
    private static final Long CACHE_TIME = 600L;

    /**
     * 字典数据同步
     * 每天0点同步
     */
    // @Scheduled(cron = "0 0/1 * * * ?")
    public void dictDataSync() {
        // cron : 0 */1 * * * ?
        logger.info("---dictDataSync task------produce Data with fixed rate task: Execution Time - {}", DateUtils.getNowDate());
        try {
            // 单位
            dictDataService.syncDataByErp(ErpApiUtil.getSLUM(),"unit");
            // 货币代码
            dictDataService.syncDataByErp(ErpApiUtil.getCurrencyCodes(),"currency_code");
            // 供应商状态代码
            dictDataService.syncDataByErp(ErpApiUtil.getVendorStatuses(),"supplier_status");
            // 账单（付款）条款
            dictDataService.syncDataByErp(ErpApiUtil.getTerms(),"terms_code");
            // 税码
            dictDataService.syncDataByErp(ErpApiUtil.getTaxCode(),"tax_rate");
            logger.info("---dictDataSync task------produce Data with fixed rate task: End Time - {}", DateUtils.getNowDate());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("dictDataSynch.task" + " | msg : " + e.getMessage());
        }
    }

    /**
     * 购方数据同步
     * 每天0点同步
     */
    //@Scheduled(cron = "0 0/1 * * * ?")
    public void buyerDataSync() {
        // cron : 0 */1 * * * ?
        logger.info("---buyerDataSync task------produce Data with fixed rate task: Execution Time - {}", DateUtils.getNowDate());
        try {
            // 单位
            tSalBuyerService.syncBuyerByErp(ErpApiUtil.getCustomers());
            logger.info("---buyerDataSync task------produce Data with fixed rate task: End Time - {}", DateUtils.getNowDate());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("buyerDataSync.task" + " | msg : " + e.getMessage());
        }
    }

    /**
     * 物料数据同步
     * 每天0点同步
     */
    //@Scheduled(cron = "0 0/4 * * * ?")
    public void materialDataSync() {
        // cron : 0 */1 * * * ?
        logger.info("---materialDataSync task------produce Data with fixed rate task: Execution Time - {}", DateUtils.getNowDate());
        try {
            // 单位
            tSalMaterialService.syncMaterialByErp(ErpApiUtil.getErpItems());
            logger.info("---materialDataSync task------produce Data with fixed rate task: End Time - {}", DateUtils.getNowDate());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("materialDataSync.task" + " | msg : " + e.getMessage());
        }
    }

    /**
     * 供应商数据同步
     * 每天0点同步
     */
    //@Scheduled(cron = "0 0/2 * * * ?")
    public void supplierDataSync() {
        // cron : 0 */1 * * * ?
        logger.info("---supplierDataSync task------produce Data with fixed rate task: Execution Time - {}", DateUtils.getNowDate());
        try {
            // 单位
            tSrmSupplierService.syncSupplierByErp(ErpApiUtil.getVendors());
            logger.info("---supplierDataSync task------produce Data with fixed rate task: End Time - {}", DateUtils.getNowDate());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("supplierDataSync.task" + " | msg : " + e.getMessage());
        }
    }

    /**
     * 订单数据同步
     * 每天0点同步
     */
    // @Scheduled(cron = "0 0/2 * * * ?")
    public void orderDataSync() {
        String busName = "订单数从ERP同步";
        String lockName = "orderDataSync";
        Date beginTime = DateUtils.getNowDate();
        try {
            Long result = redisCache.incrAndExpire(lockName , CACHE_TIME);
            logger.info("{}, 获取并发锁结果 {}", busName, result);
            if (result > 1) {
                logger.info("不予触发");
                return;
            }
            tSalOrderService.syncOrderByErp(ErpApiUtil.getOrders());
        } catch (Exception e) {
            Date endTime = DateUtils.getNowDate();
            e.printStackTrace();
            logger.info("{}任务执行异常,耗时：{} 毫秒", busName, endTime.getTime()-beginTime.getTime());
        } finally {
            // 释放锁
            redisCache.deleteObject(lockName);
        }
    }

    /**
     * 结算单数据同步
     * 每天0点同步
     */
    //@Scheduled(cron = "0 0/2 * * * ?")
    public void settlebillDataSync() {
        String busName = "结算单数从ERP同步";
        String lockName = "settlebillDataSync";
        Date beginTime = DateUtils.getNowDate();
        try {
            Long result = redisCache.incrAndExpire(lockName , CACHE_TIME);
            logger.info("{}, 获取并发锁结果 {}", busName, result);
            if (result > 1) {
                logger.info("不予触发");
                return;
            }
            tScSettlebillService.syncSettlebillByErp(ErpApiUtil.getSettlebill());
        } catch (Exception e) {
            Date endTime = DateUtils.getNowDate();
            e.printStackTrace();
            logger.info("{}任务执行异常,耗时：{} 毫秒", busName, endTime.getTime()-beginTime.getTime());
        } finally {
            // 释放锁
            redisCache.deleteObject(lockName);
        }
    }

    /**
     * 结算单开票状态回写同步
     * 每天0点同步
     */
    //@Scheduled(cron = "0 0/2 * * * ?")
    public void settlebillWirteBackSync() {
        String busName = "结算单开票状态回写同步";
        String lockName = "settlebillWirteBackSync";
        Date beginTime = DateUtils.getNowDate();
        try {
            Long result = redisCache.incrAndExpire(lockName , CACHE_TIME);
            logger.info("{}, 获取并发锁结果 {}", busName, result);
            if (result > 1) {
                logger.info("不予触发");
                return;
            }
            tScSettlebillService.syncSettlebillWirteBackByErp();
        } catch (Exception e) {
            Date endTime = DateUtils.getNowDate();
            e.printStackTrace();
            logger.info("{}任务执行异常,耗时：{} 毫秒", busName, endTime.getTime()-beginTime.getTime());
        } finally {
            // 释放锁
            redisCache.deleteObject(lockName);
        }
    }


}
